package com.jzo2o.trade.service.impl;

import cn.hutool.core.img.ImgUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.Config;
import com.alipay.easysdk.kernel.util.ResponseChecker;
import com.alipay.easysdk.payment.facetoface.models.AlipayTradePrecreateResponse;
import com.jzo2o.api.trade.dto.response.PayResDTO;
import com.jzo2o.api.trade.enums.PayTypeEnum;
import com.jzo2o.trade.model.domain.Trading;
import com.jzo2o.trade.service.IAliPayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class AliPayServiceImpl implements IAliPayService {

    @Autowired
    private Config config;

    @Override
    public PayResDTO pay(Trading trading) {
        if (PayTypeEnum.NATIVE.getValue().equals(trading.getTradingType())) {
            log.info("支付宝扫码支付");
            return payNative(trading);
        }
        return null;
    }

    private PayResDTO payNative(Trading trading) {
        log.info("开始调用支付扫码宝接口");
        // 1. 设置参数（全局只需设置一次）
        Factory.setOptions(config);
        PayResDTO payResDTO = new PayResDTO();
        try {
            // 2. 发起API调用（以创建当面付收款二维码为例）
            AlipayTradePrecreateResponse response = Factory.Payment.FaceToFace()
                    .preCreate(trading.getMemo(), trading.getTradingOrderNo(), String.valueOf(trading.getTradingAmount()));
            // 3. 处理响应或异常
            if (ResponseChecker.success(response)) {
                String url = response.qrCode;
                //hutool 工具转换二维码
                String qrBase64 = QrCodeUtil.generateAsBase64(url, new QrConfig(), ImgUtil.IMAGE_TYPE_PNG);
                payResDTO.setQrCode(qrBase64);
                payResDTO.setPayOrderNo(trading.getTradingOrderNo());
                return payResDTO;
            } else {
                log.error("调用失败，原因：" + response.msg + "，" + response.subMsg);
                return null;
            }
        } catch (Exception e) {
            log.error("调用遭遇异常，原因：" + e.getMessage());
            throw new RuntimeException(e.getMessage(), e);
        }
    }
}
